<template>
  <div class="sp-template">
    <el-card class="box-card">
      <el-checkbox v-model="fbaChecked" style="margin-left:20px;" @change="addressCheckboxChange">FBA地址</el-checkbox>
      <el-form ref="orderForm2" label-position="top" :model="orderForm.consigneeAddress" size="small" :rules="orderFormRule2">
        <el-row :gutter="gutter">
          <el-col :span="12">
            <el-form-item label="客户单号" prop="customerRef" class="is-required">
              <el-input v-model.trim="orderForm.customerRef" auto-complete="off" placeholder="由系统提供，可修改" />
            </el-form-item>
          </el-col>
          <el-col v-if="fbaChecked" :span="12">
            <el-form-item label="FBA仓码">
              <el-select v-model.trim="orderForm.consigneeAddress.fbaCode" filterable style="width:100%" @change="fbaCodeSelectChange">
                <el-option v-for="(fba,i) in fbaAddress" :key="i" class="fbacode-item" :label="fba.fbaCode" :value="fba.fbaCode" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col v-else :span="12">
            <el-form-item label="常用地址">
              <el-select v-model.trim="ownerAddressSelectId" filterable style="width:100%" @change="ownerAddressSelectChange">
                <el-option v-for="(item,i) in ownerAddress" :key="i" :label="item.shortName" :value="item.id" />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row v-show="!fbaChecked" :gutter="gutter">
          <el-col :span="12">
            <el-form-item prop="contacter" class="is-required">
              <slot name="label">
                联系人
                <el-tooltip effect="light" content="输入内容仅支持：英文字母、数字，英文状态下的句号、逗号、下划线、短横线、空格和&，且长度不能超过35位" placement="top">
                  <i class="el-icon-warning" />
                </el-tooltip>
              </slot>
              <el-input v-model="orderForm.consigneeAddress.contacter" auto-complete="off" placeholder="如已存在联系人，则自动补充后面信息" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="联系电话" prop="phone" class="is-required">
              <el-input v-model.trim="orderForm.consigneeAddress.phone" auto-complete="off" placeholder="联系电话" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="gutter">
          <el-col :span="12">
            <el-form-item label="目的国家" prop="countryCode" class="is-required">
              <el-select v-model="orderForm.consigneeAddress.countryCode" filterable style="width:100%">
                <el-option v-for="(item,i) in countrys" :key="i" :label="item.nameCn" :value="item.code" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="省/州" prop="state" class="is-required">
              <el-input v-model="orderForm.consigneeAddress.state" auto-complete="off" placeholder="根据仓码自动匹配" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="gutter">
          <el-col :span="12">
            <el-form-item prop="city" class="is-required">
              <slot name="label">
                目的城市
                <el-tooltip effect="light" content="输入内容仅支持：英文字母、数字，英文状态下的句号、逗号、下划线、短横线、空格和&，且长度不能超过35位" placement="top">
                  <i class="el-icon-warning" />
                </el-tooltip>
              </slot>
              <div>
                <el-input v-model="orderForm.consigneeAddress.city" auto-complete="off" placeholder="根据仓码自动匹配，可修改" />
              </div>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="目的邮编" prop="zipCode" class="is-required">
              <el-input v-model.trim="orderForm.consigneeAddress.zipCode" auto-complete="off" placeholder="根据仓码自动匹配，可修改" @input="queryFbaAddressByZipcode" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row v-show="!fbaChecked" :gutter="gutter">
          <el-col :span="12">
            <el-form-item prop="company">
              <slot name="label">
                公司名称
                <el-tooltip effect="light" content="输入内容仅支持：英文字母、数字，英文状态下的句号、逗号、下划线、短横线、空格和&，且长度不能超过35位" placement="top">
                  <i class="el-icon-warning" />
                </el-tooltip>
              </slot>
              <div>
                <el-input v-model="orderForm.consigneeAddress.company" auto-complete="off" placeholder="公司名称" />
              </div>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="gutter">
          <el-col :span="12">
            <el-form-item prop="address" class="is-required">
              <slot name="label">
                详细地址1
                <el-tooltip effect="light" content="输入内容仅支持：英文字母、数字，英文状态下的句号、逗号、下划线、短横线、空格和&，且长度不能超过35位" placement="top">
                  <i class="el-icon-warning" />
                </el-tooltip>
              </slot>
              <el-input v-model="orderForm.consigneeAddress.address" auto-complete="off" class="width50" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item prop="address2">
              <slot name="label">
                详细地址2
                <el-tooltip effect="light" content="输入内容仅支持：英文字母、数字，英文状态下的句号、逗号、下划线、短横线、空格和&，且长度不能超过35位" placement="top">
                  <i class="el-icon-warning" />
                </el-tooltip>
              </slot>
              <el-input v-model="orderForm.consigneeAddress.address2" auto-complete="off" class="width50" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="gutter">
          <el-col :span="12">
            <el-form-item label="产品名称" prop="channelId">
              <el-select v-model="orderForm.channelId" style="width:100%">
                <el-option v-for="(p,i) in channelOptions" :key="i" :label="p.name" :value="p.id" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="货物箱数" prop="totalCarton">
              <el-input v-model="orderForm.totalCarton" auto-complete="off" type="number" placeholder="货物箱数" />
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="总重量(kg)">
              <el-input v-model="allWeight" auto-complete="off" placeholder="总重量" :readonly="true" :disabled="true" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col v-show="!orderDataFromEditer" :span="24">
            <el-form-item label="申报信息">
              <el-upload :action="baseUrl" :on-success="uploadCallBack" name="file" :limit="1" :file-list="fileList" accept=".xlsx" :with-credentials="true" :show-file-list="false" style="display: inline-block;">
                <el-button slot="trigger" size="small" type="primary">选取文件</el-button>
              </el-upload>
              <a :href="downloadTemp" download="packing_list.xlsx" style="margin-left:50px;display: inline-block; vertical-align: top;">
                <el-button size="small" type="text">下载模板</el-button>
              </a>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row v-show="cartonList.length>0">
          <el-table :data="cartonList" :span-method="cartonTableSpanMethod" border style="width: 100%">
            <el-table-column prop="length" label="长" />
            <el-table-column prop="width" label="宽" />
            <el-table-column prop="height" label="高" />
            <el-table-column prop="weight" label="重量" />
            <el-table-column prop="sameSpecCartons" label="箱数" />
            <el-table-column prop="skuNameEn" label="英文品名" />
            <el-table-column prop="skuNameCn" label="中文品名" />
            <el-table-column prop="qty" label="数量" />
            <el-table-column prop="skuWeight" label="sku重量" />
            <el-table-column prop="unitPrice" label="申报单价" />
            <el-table-column prop="currency" label="币种" />
          </el-table>
        </el-row>
        <el-row class="theTable2">
          <el-col :span="24">
            <el-table
              :key="Math.random()"
              :data="cartonList2"
              stripe
              border
              style="width: 100%"
              :header-cell-style="{'text-align':'center'}"
              :cell-style="{'text-align':'center'}"
              show-summary
              :summary-method="getSummaries"
              :header-row-style="{height:'30px'}"
              :row-style="{height:'25px'}"
            >
              <el-table-column type="index" label=" " width="50" align="center" />
              <el-table-column :key="Math.random()" prop="length" label="长(cm)" width="110">
                <template slot-scope="scope">
                  <el-input v-model="scope.row.length" style="width: 100%; height: 100%;" />
                </template>
              </el-table-column>
              <el-table-column :key="Math.random()" prop="width" label="宽(cm)" width="110">
                <template slot-scope="scope">
                  <el-input v-model="scope.row.width" style="width: 100%; height: 100%;" />
                </template>
              </el-table-column>
              <el-table-column :key="Math.random()" prop="height" label="高(cm)" width="110">
                <template slot-scope="scope">
                  <el-input v-model="scope.row.height" style="width: 100%; height: 100%;" />
                </template>
              </el-table-column>
              <el-table-column :key="Math.random()" prop="weight" label="重(kg)" width="110">
                <template slot-scope="scope">
                  <el-input v-model="scope.row.weight" style="width: 100%; height: 100%;" />
                </template>
              </el-table-column>
              <el-table-column :key="Math.random()" prop="qty" label="箱数" width="110">
                <template slot-scope="scope">
                  <el-input v-model="scope.row.qty" style="width: 100%; height: 100%;" />
                </template>
              </el-table-column>

              <el-table-column :key="Math.random()" label="操作" width="100">
                <template slot-scope="scope">
                  <i v-show="scope.$index>0" class="el-icon-remove-outline" title="删除" @click="cartonList2.splice(scope.$index, 1)" />
                  <i v-show="scope.$index==0" class="el-icon-circle-plus-outline" title="新增" @click="addCartonRow" />
                </template>
              </el-table-column>
            </el-table>
          </el-col>
        </el-row>

        <el-row v-if="showRate">
          <h3 class="sp-card-title">试算运费</h3>
          <el-form-item>
            <el-table
              ref="multipleTable"
              :data="rateData"
              style="width: 100%"
              :header-cell-class-name="cellClass"
              border
              @select="onRateTableSelect"
            >
              <el-table-column type="selection" width="55" />
              <el-table-column prop="channelName" label="产品" />
              <el-table-column prop="totalAmount" label="合计" />
              <el-table-column label="费用类型">
                <template slot-scope="scope">
                  <div v-for="(d,i) in scope.row.txs" :key="i" class="charge-item">{{ d.chargeName }}</div>
                </template>
              </el-table-column>
              <el-table-column label="币种">
                <template slot-scope="scope">
                  <div v-for="(d,i) in scope.row.txs" :key="i" class="charge-item">USD</div>
                </template>
              </el-table-column>
              <el-table-column label="价格">
                <template slot-scope="scope">
                  <div v-for="(d,i) in scope.row.txs" :key="i" class="charge-item">{{ d.amount }}</div>
                </template>
              </el-table-column>
            </el-table>
          </el-form-item>
        </el-row>
        <el-row type="flex" class="row-bg" justify="space-around">
          <el-form-item style="margin-top:20px;">
            <el-button size="small" type="primary" @click="createOrderSubmit(false)">确 定</el-button>
            <el-button v-show="!orderDataFromEditer" size="small" type="primary" @click="createOrderSubmit(true)">试算运费</el-button>
          </el-form-item>
        </el-row>
      </el-form>
    </el-card>

  </div>
</template>

<script>
import request from '@/utils/request'
import { copyProperty, copyAllProperty } from '@/utils/tools'
import config from '@/settings'
import { mapState } from 'vuex'
const BASE_URL = process.env.NODE_ENV === 'development' ? config.baseUrl.dev : config.baseUrl.pro

export default {
  props: {
    orderDataFromEditer: {
      type: Object
    },
    cartonListFromEditer: {
      type: Array
    }
  },
  data() {
    return {
      baseUrl: BASE_URL + '/order/parse2',
      ownerAddressSelectId: '',
      gutter: 100,
      fileList: [],
      cartonList: [],
      downloadTemp: '/template/packing_list.xlsx',
      fbaChecked: true,
      isTruck: false, // 是否卡车
      consigneeAddressDefault: {
        contacter: '',
        phone: '',
        countryCode: 'US',
        state: '',
        city: '',
        address: '',
        address2: '',
        company: '',
        zipCode: '',
        fbaCode: '',
        deliverySignature: 'false'
      },
      orderForm: {
        channelId: '',
        customerRef: '',
        consigneeAddress: {
          contacter: '',
          phone: '',
          countryCode: 'US',
          state: '',
          city: '',
          address: '',
          address2: '',
          company: '',
          zipCode: '',
          fbaCode: '',
          deliverySignature: 'false'
        },
        totalCarton: '',
        cartons: []
      },
      rateData: [],
      showRate: false,
      orderFormRule2: {
        customerRef: [
          {
            validator: (rule, value, callback) => {
              if (this.orderForm.customerRef === '' || this.orderForm.customerRef.length > 30) {
                callback(new Error('客户单号必填且长度不能大于30'))
                return
              }
              callback()
            },
            trigger: 'change'
          }
        ],
        contacter: [{ required: true, message: '请输入联系人', trigger: 'blur' }],
        phone: [{ required: true, message: '请输入电话', trigger: 'change' }],
        countryCode: [{ required: true, message: '请输入国家', trigger: 'change' }],
        state: [{ required: true, message: '请输入州/省', trigger: 'change' }],
        city: [{ required: true, message: '请输入城市', trigger: 'blur' }],
        address: [{ required: true, message: '请输入地址', trigger: 'blur' }],
        zipCode: [{ required: true, message: '请输入邮编', trigger: 'blur' }]
      },
      isFba: true,
      fbaAddress: [],
      fbaCodeToAddress: new Map(),
      ownerAddress: [],
      ownerAddressIdToAddress: new Map(),
      channelProduct: [],
      channelCodeMap: {},
      countrys: [],
      cartonList2: [{ length: '', width: '', height: '', weight: '', qty: '' }]
    }
  },
  computed: {
    ...mapState(
      {
        paymentTerm: state => state.base.paymentTerm,
        customerOptions: state => state.base.customerOptions,
        channelOptions: state => state.base.channelOptions
      }),
    allWeight() {
      let weight = 0
      this.orderForm.cartons.forEach(c => {
        weight += c.weight * c.sameSpecCartons
      })
      return weight
    },
    editing: {
      get() {
        return this.orderDataFromEditer && this.orderDataFromEditer.editing
      }
    }
  },
  watch: {
    editing: function() {
      if (this.orderDataFromEditer) {
          copyAllProperty(this.orderForm, this.orderDataFromEditer, true)
          this.cartonList = this.cartonListFromEditer
          if (this.orderForm.consigneeAddress.fbaCode) {
            this.fbaChecked = true
          } else {
            this.fbaChecked = false
          }
      }
    }
  },
  created() {
    this.queryCountrys()
    this.queryFbaAddress()
    if (this.orderDataFromEditer) {
          copyAllProperty(this.orderForm, this.orderDataFromEditer, true)
          this.cartonList = this.cartonListFromEditer
          if (this.orderForm.consigneeAddress.fbaCode) {
            this.fbaChecked = true
          } else {
            this.fbaChecked = false
          }
    }
  },
  methods: {
    cartonTableSpanMethod(row) {
      if (row.row.rowSpan > 0 && row.columnIndex <= 4) {
        return [row.row.rowSpan, 1]
      } else if (row.columnIndex > 4) {
        return [1, 1]
      } else if (row.columnIndex <= 4) {
        return [0, 1]
      }
    },
    uploadCallBack(res) {
      if (!res.success) {
        this.$message({
          showClose: true,
          message: res.message,
          type: 'error',
          duration: 0
        })
        this.fileList = []
        return
      }
      this.cartonList = res.data.flatValues
      this.orderForm.cartons = res.data.values
      this.fileList = []
    },
    addressCheckboxChange(v) {
      copyProperty(this.orderForm.consigneeAddress, this.consigneeAddressDefault)
      if (v || this.ownerAddress.length > 0) {
        return
      }
      // 加载常用地址
      request({
        url: '/basesetting/owner/deliver/all',
        method: 'get'
      }).then(res => {
        if (res.success) {
          this.ownerAddress = res.data
          res.data.forEach(ele => {
            this.ownerAddressIdToAddress.set(ele.id, ele)
          })
        }
      })
    },
    back() {
      this.$router.go(-1)
    },
    queryCountrys() {
      request({
        url: '/countrys',
        method: 'get'
      }).then(res => {
        if (res.success) {
          if (res.data) {
            this.countrys = res.data
          }
        }
      })
    },
    createOrderSubmit(rate) {
      this.orderForm.rate = rate
      let ruleValid = false
      this.$refs['orderForm2'].validate(valid => {
        ruleValid = valid
      })
      if (!ruleValid) {
        return
      }
      if (!rate && (!this.orderForm.channelId || this.orderForm.channelId === '')) {
        this.$message.error('请选择产品')
        return
      }
      if (!this.orderForm.totalCarton || this.orderForm.totalCarton === '') {
        this.$message.error('请输入总箱数')
        return
      }

      if (this.orderForm.cartons.length === 0) {
        this.$message.error('请上传申报信息')
        return
      }
      let totalCarton = 0
      this.orderForm.cartons.forEach(ele => {
        totalCarton += ele.sameSpecCartons
      })

      if (this.orderForm.totalCarton === '' || parseInt(this.orderForm.totalCarton) !== totalCarton) {
        this.$message.error('箱数和申报箱数不一致')
        return
      }

      if (rate) {
        const loading = this.$loading({
          lock: true,
          text: 'Loading',
          spinner: 'el-icon-loading',
          background: 'rgba(0, 0, 0, 0.7)'
        })
        request({
          url: 'charge/rate',
          method: 'post',
          data: this.orderForm
        }).then(res => {
          loading.close()
          this.showRate = true
          this.rateData = res.data
        })
      } else {
        let url = 'order'
        if (this.orderDataFromEditer) {
          url = 'order/edit'
        }
        request({
          url: url,
          method: 'post',
          data: this.orderForm
        }).then(res => {
          this.$message.success('成功')
          copyProperty(this.orderForm.consigneeAddress, this.consigneeAddressDefault)
          this.cartonList = []
          this.orderForm.cartons = []
          this.showRate = false
          this.rateData = []
        })
      }
    },
    fbaCodeSelectChange(fbaCode) {
      const d = this.fbaCodeToAddress.get(fbaCode)
      copyProperty(this.orderForm.consigneeAddress, d)
    },
    ownerAddressSelectChange(id) {
      const d = this.ownerAddressIdToAddress.get(id)
      copyProperty(this.orderForm.consigneeAddress, d)
    },
    queryFbaAddress() {
      request({
        url: '/basesetting/op/fba/all',
        method: 'get'
      }).then(res => {
        if (res.success) {
          this.fbaAddress = res.data
          res.data.forEach(ele => {
            this.fbaCodeToAddress.set(ele.fbaCode, ele)
          })
        }
      })
    },
    queryFbaAddressByZipcode() {
    },
    cellClass(row) {
      if (row.columnIndex === 0) {
        return 'DisabledSelection'
      }
    },
    onRateTableSelect(rows, row) {
      if (rows.length > 0) {
        this.orderForm.channelId = row.channelId
        this.$refs.multipleTable.clearSelection()
        this.$refs.multipleTable.toggleRowSelection(row)
      } else {
        this.orderForm.channelId = ''
      }
    },
    chargeSum(charges) {
      let sum = 0
      charges.forEach((item, index) => {
        sum += item.amount
      })
      return sum.toFixed(2)
    },
    // 表尾合计
    getSummaries(param) {
      const { columns } = param
      const sums = []
      columns.forEach((column, index) => {
        if (index === 0) {
          sums[index] = '合计'
          return
        }
        if (this.cartonList2.length > 0) {
          if (column.property === 'weight') {
            sums[index] = Number(this.cartonList2.map(a => a.weight && a.qty ? parseFloat(a.weight) * parseInt(a.qty) : 0).reduce((n, m) => n + m)).toFixed(2)
          }
          if (column.property === 'qty') {
            sums[index] = Number(this.cartonList2.map(a => a.qty ? parseInt(a.qty) : 0).reduce((n, m) => n + m))
          }
        } else {
          sums[index] = ''
        }
      })
      return sums
    },
    addCartonRow() {
      this.cartonList2.push({ length: '', width: '', height: '', weight: '', qty: '' })
    }
  }
}
</script>

<style lang="scss" scoped>
#sp-amap {
  position: fixed;
  top: 0;
  right: 100%;
  &.isOpen {
    position: relative;
    right: 0;
  }
}
.sku-item {
  margin: 0 -10px;
  padding: 5px 10px;
  &:not(:last-child) {
    border-bottom: 1px dashed #ccc;
  }
}
.el-table .DisabledSelection .cell .el-checkbox__inner {
  display: none;
  position: relative;
}

.el-table .DisabledSelection .cell:before {
  position: absolute;
  right: 11px;
}

.el-table .cell {
  .charge-item {
    height: 34px;
    line-height: 34px;
    margin: 0 -10px;
    padding: 0 10px;
    overflow: hidden;
    text-overflow: ellipsis;
    white-space: nowrap;
    border-bottom: 1px solid #ebeef5;
  }
  > .charge-item:first-child {
    margin-top: -10px;
  }
  > .charge-item:last-child {
    border-bottom: none;
    margin-bottom: -10px;
  }
}
</style>
<style>
  #toolpanel .el-input {
    width: 130px;
  }

  .el-divider {
    margin: 8px 0;
    background: 0 0;
    border-top: 1px solid #E6EBF5;
  }

  .tool-select-div .el-input {
    width: 130px;
  }

  .theTable2 .el-table__footer-wrapper table{
    text-align: center;
  }
  /* /deep/ 为深度操作符，可以穿透到子组件 */
  .theTable2 .el-table {
  display: flex;
  flex-direction: column;
}

/* order默认值为0，只需将表体order置为1即可移到最后，这样合计行就上移到表体上方 */
.theTable2 .el-table__body-wrapper {
  order: 0;
}

.theTable2 .el-table th{
    padding: 0 !important;
}
.theTable2 .el-table td{
    padding: 0 !important;
}
.theTable2 .el-table .cell{
    padding: 0 !important;
}
.theTable2 .el-input__inner{
  height: 27px !important;
  line-height: 27px !important;
  text-align: center;
}

</style>
